package com.lu.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @program ElasticsearchLearn
 * @description: Ik分词器热加载
 *
 *  Elastic：IK分词器分词、停用词热更新如何配置（一）基于API: https://blog.csdn.net/qq_24950043/article/details/121962723
 *  Elastic：IK分词器分词、停用词热更新如何配置（二）基于数据库: https://blog.csdn.net/qq_24950043/article/details/121982269
 * @author: zhanglu
 * @create: 2022-06-29 17:38:00
 */
@Slf4j
@RequestMapping("/iK-tokenizer/hot-loading")
@RestController
public class IKTokenizerHotLoadingController {

    /*
        es默认1m更新一次
        GET /_analyze
        {
        "text": "超级喜欢幸仁杰",
        "analyzer": "ik_max_word"
        }
     */
    @GetMapping("/ext-dict")
    public String extDict(HttpServletResponse response){
        log.info("获取远程词典");
        File file = new File("/Users/zhanglu/Desktop/lu/workspace/dev_workspace/idea/框架/ElasticsearchLearn/software/elasticsearch-7.11.1/plugins/ik/config/customer/remote_ext_dict.dic");
        //优化读取文本内容的方法：不受int长度的显示
        byte[] buffer = new byte[(int)file.length()];
        final String res = FileUtil.readString(file, CharsetUtil.UTF_8);
        long lastModified = file.lastModified();
        String etag = '"' + Long.toHexString(lastModified) + '-' + Long.toHexString(buffer.length) + '"';
        response.setHeader("Last-Modified",String.valueOf(lastModified));
        response.setHeader("ETag",etag);
        response.setContentType("text/plain;charset=utf-8");
        return res;
    }

    @GetMapping("/ext-stopwords")
    public String extStopwords(HttpServletResponse response){
        log.info("获取远程停用词");
        File file = new File("/Users/zhanglu/Desktop/lu/workspace/dev_workspace/idea/框架/ElasticsearchLearn/software/elasticsearch-7.11.1/plugins/ik/config/customer/remote_ext_stopwords.dic");
        //优化读取文本内容的方法：不受int长度的显示
        byte[] buffer = new byte[(int)file.length()];
        final String res = FileUtil.readString(file, CharsetUtil.UTF_8);
        long lastModified = file.lastModified();
        String etag = '"' + Long.toHexString(lastModified) + '-' + Long.toHexString(buffer.length) + '"';
        response.setHeader("Last-Modified",String.valueOf(lastModified));
        response.setHeader("ETag",etag);
        response.setContentType("text/plain;charset=utf-8");
        return res;
    }

}
